<?php

$record_obj = new record_obj();
$client_obj = new client_obj();
$tariff_obj = new tariff_obj();

if (!isset($_REQUEST['id']) || !is_numeric($_REQUEST['id'])) {
    error_obj::setError(new error_obj("bad request id", __FILE__, 'line 4 -> redirect'), UNEXCEPTED);
    base_obj::redirect(ROOT);
}

$recordId = (int) $_REQUEST['id'];

if (isset($_REQUEST['action']) && !empty($_REQUEST['action'])){
    if ($_REQUEST['action']=='edit_record') {
        $in_data = $_REQUEST['record'];
        $in_data['unit_price'] = $in_data['price'];
        unset($in_data['price']);
        $in_data['date'] = base_obj::convertDateTo($in_data['date']);
        $result = $record_obj->editRecord($in_data, $recordId);
        if (error_obj::isError($result)){
            error_obj::setError($result, UNEXCEPTED);
        } else {
            base_obj::redirect(ROOT . '?input=timesheets');
        }
    }
}

$record_data = $record_obj->getRecordById($recordId);

if (error_obj::isError($record_data))
    error_obj::setError($record_data, UNEXCEPTED);
elseif (empty($record_data))
    error_obj::setError(new error_obj("empty record", __FILE__, 'get task data'), EMPTY_RECORD);
else {
    base_obj::debug("record data", $record_data);
        
    $record_data['date'] = base_obj::convertDateTo($record_data['date'], 'dd/mm/yyyy', 'date');
    
    $month = date("m");
    $year = date("Y");
    $db_obj = new db_obj();
    $res = $client_obj->getClient($record_data['client'], array('conditions'));

    $text = '';

    if (!error_obj::isError($res) && !empty($res)) {
        $text .= '<div><h3>Conditions:</h3>';
        if (empty($res['conditions']))
            $text .= '-';
        else
            $text .= $res['conditions'];
        $text .= '</div>';
    }

    $sql = "SELECT SUM(amount) AS s FROM " . $GLOBALS['tb_records'] . " WHERE client=" . $record_data['client'] . " AND DATE_FORMAT(date, '%m')='" . $month . "' AND DATE_FORMAT(date, '%Y')='" . $year . "'";
    $res = $db_obj->getOne($sql);
    if (!error_obj::isError($res) && !empty($res)) {
        $text .= '<div><h3>Used amount in ' . $month . '/' . $year . ':</h3>';
        $text .= $res;
        $text .= '</div>';
    } else {
        $text .= '<div><h3>Used amount in ' . $month . '/' . $year . ':</h3>';
        $text .= '0';
        $text .= '</div>';
    }
    
    $record_data['report'] = $text;
    $GLOBALS['template_data']['record_data'] = $record_data;
    
    $filter = array();
    $filter['active'] = 0;
    $GLOBALS['template_data']['clients'] = $client_obj->getAllClients('klient_id, name', $filter, 'name ASC');
    $GLOBALS['template_data']['types'] = $record_obj->getRecordTypes();
    $filter = array();
    $filter['type_of_record'] = 1;
    $GLOBALS['template_data']['tariffs'] = $tariff_obj->getTariffs("Id, title", $filter, 'title ASC');
}
?>
